<?php
/**
 * @since   2022-02-20
 * @author  zhaoxiang <zhaoxiang051405@gmail.com>
 */

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Middleware\AdminMiddleware;
use App\Model\AdminUserAction;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use function Hyperf\Config\config;

#[Controller(prefix: '/admin/Log'), Middleware(AdminMiddleware::class)]
class LogController extends BaseController {

    /**
     * 获取日志列表
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'index')]
    public function index(): array {
        $limit = $this->request->query('size', config('apiadmin.admin_list_default'));
        $keywords = $this->request->query('keywords', '');
        $type = $this->request->query('type', '');

        $obj = AdminUserAction::query();
        if ($type) {
            switch ($type) {
                case 1:
                    $obj = $obj->where('url', 'like', "%{$keywords}%");
                    break;
                case 2:
                    $obj = $obj->where('nickname', 'like', "%{$keywords}%");
                    break;
                case 3:
                    $obj = $obj->where('uid', $keywords);
                    break;
            }
        }
        $listObj = $obj->orderByDesc('add_time')->paginate((int)$limit);

        return $this->buildSuccess([
            'list'  => $listObj->items(),
            'count' => $listObj->total()
        ]);
    }

    /**
     *
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'del')]
    public function del(): array {
        $id = $this->request->query('id', '');
        if (!$id) {
            return $this->buildFailed(ErrorCode::EMPTY_PARAMS, '缺少必要参数');
        }
        AdminUserAction::destroy($id);

        return $this->buildSuccess();
    }

}
